package interlocking.ui;

import interlocking.controller.InterlockingController;
import interlocking.model.*;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.Timer;
public class ControlPanel extends JPanel{

    private final InterlockingController controller;

    private JComboBox<String> switchSelector;
    private JComboBox<String> signalSelector;
    private JComboBox<String> trackSelector;
    private Map<String, Signal> signals ;
    private Timer animationTimer;
    public ControlPanel(InterlockingController controller) {
        this.controller = controller;
        initializeUI();
    }


    private void initializeUI() {
        setLayout(new GridLayout(0, 1, 5, 5));
        setBorder(BorderFactory.createTitledBorder("联锁控制系统"));
        setPreferredSize(new Dimension(300, 600));

        // 初始化设备选择器
        initDeviceSelectors();

        // 添加功能按钮
        addOperationButtons();

        // 添加状态显示
        addStatusDisplay();
    }

    private void initDeviceSelectors() {
        // 道岔选择器
        Map<String, Switch> switches = controller.getSwitches();
        switchSelector = new JComboBox<>(switches.keySet().toArray(new String[0]));
        add(new JLabel("选择道岔:"));
        add(switchSelector);

        // 信号机选择器

        //Map<String, Signal> signals = controller.getSignals();
        this.signals=controller.getSignals();
        signalSelector = new JComboBox<>(signals.keySet().toArray(new String[0]));
        add(new JLabel("选择信号机:"));
        add(signalSelector);

        // 轨道区段选择器
        Map<String, TrackCircuit> tracks = controller.getTrackCircuits();
        trackSelector = new JComboBox<>(tracks.keySet().toArray(new String[0]));
        add(new JLabel("选择轨道区段:"));
        add(trackSelector);
    }

    private void addOperationButtons() {
        // 道岔操作按钮
        add(new JLabel("道岔操作:"));
        JButton normalBtn = new JButton("定位");
        normalBtn.addActionListener(e -> {
            String switchId = (String) switchSelector.getSelectedItem();
            controller.setSwitchPosition(switchId, Switch.SwitchPosition.NORMAL);
        });
        add(normalBtn);

        JButton reverseBtn = new JButton("反位");
        reverseBtn.addActionListener(e -> {
            String switchId = (String) switchSelector.getSelectedItem();
            controller.setSwitchPosition(switchId, Switch.SwitchPosition.REVERSE);
        });
        add(reverseBtn);

        JButton lockBtn = new JButton("单锁");
        lockBtn.addActionListener(e -> {
            String switchId = (String) switchSelector.getSelectedItem();
            controller.lockSwitch(switchId);
        });
        add(lockBtn);

        // 信号机操作按钮
        add(new JLabel("信号机操作:"));
        //Map<String, Signal> signals = controller.getSignals();
        JButton stopBtn = new JButton("红灯");
        stopBtn.addActionListener(e -> {
            String signalId = (String) signalSelector.getSelectedItem();
            if("P1".equals(signalId)||"P2".equals(signalId)){
                JOptionPane.showMessageDialog(this, "禁止修改P1/P2的信号灯！", "警告", JOptionPane.WARNING_MESSAGE);
                return;
            }
            controller.setSignalAspect(signalId, Signal.SignalAspect.STOP);


           // System.out.println(controller.check(signals));
            if(!controller.check(signals)){
                controller.setSignalAspect("P1", Signal.SignalAspect.STOP);
                controller.setSignalAspect("P2", Signal.SignalAspect.STOP);
            }

        });
        add(stopBtn);

        JButton proceedBtn = new JButton("绿灯");
        proceedBtn.addActionListener(e -> {
            String signalId = (String) signalSelector.getSelectedItem();
            if("P1".equals(signalId)||"P2".equals(signalId)){
                JOptionPane.showMessageDialog(this, "禁止修改P1/P2的信号灯！", "警告", JOptionPane.WARNING_MESSAGE);
                return;
            }
            controller.setSignalAspect(signalId, Signal.SignalAspect.PROCEED);

            //检查是否有能够停靠的轨道
           if(controller.check(signals)){
               controller.setSignalAspect("P1", Signal.SignalAspect.PROCEED);
               controller.setSignalAspect("P2", Signal.SignalAspect.PROCEED);
           }

        });
        add(proceedBtn);

        // 轨道区段操作按钮
        add(new JLabel("轨道操作:"));
        JButton occupyBtn = new JButton("占用");
        occupyBtn.addActionListener(e -> {
            String trackId = (String) trackSelector.getSelectedItem();
            controller.setTrackCircuitOccupied(trackId, true);
        });
        add(occupyBtn);

        JButton clearBtn = new JButton("出清");
        clearBtn.addActionListener(e -> {
            String trackId = (String) trackSelector.getSelectedItem();
            //在这里添加对轨道区段的判断，判断是否可以变化
            switch (trackId) {
                case "T1": {
                    Signal signal1 = signals.get("S1");
                    Signal signal2 = signals.get("S2");
                    if (signal1.getAspect() == Signal.SignalAspect.PROCEED &&
                            signal2.getAspect() == Signal.SignalAspect.PROCEED) {
                        controller.setTrackCircuitOccupied(trackId, true);
                    } else {
                        JOptionPane.showMessageDialog(this, "信号机S1和S2为红色！",
                                "警告", JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                    break;
                }
                case "T2": {
                    Signal signal3 = signals.get("S3");
                    Signal signal4 = signals.get("S4");
                    if (signal3.getAspect() == Signal.SignalAspect.PROCEED &&
                            signal4.getAspect() == Signal.SignalAspect.PROCEED) {
                        controller.setTrackCircuitOccupied(trackId, true);
                    } else {
                        JOptionPane.showMessageDialog(this, "信号机S3和S4为红色！",
                                "警告", JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                    break;
                }
                case "T3": {
                    Signal signal5 = signals.get("S5");
                    Signal signal6 = signals.get("S6");
                    if (signal5.getAspect() == Signal.SignalAspect.PROCEED &&
                            signal6.getAspect() == Signal.SignalAspect.PROCEED) {
                        controller.setTrackCircuitOccupied(trackId, true);
                    } else {
                        JOptionPane.showMessageDialog(this, "信号机S5和S6为红色！",
                                "警告", JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                    break;
                }
                default:
                    JOptionPane.showMessageDialog(this, "无效的轨道ID: " + trackId,
                            "错误", JOptionPane.ERROR_MESSAGE);
                    return;
            }
//            if(trackId=="T1"){
//                Signal signal1=signals.get("S1");
//                Signal signal2=signals.get("S2");
//                if(signal1.getAspect()== Signal.SignalAspect.PROCEED&&signal2.getAspect()== Signal.SignalAspect.PROCEED){
//                    controller.setTrackCircuitOccupied(trackId, true);
//                }else {
//                    JOptionPane.showMessageDialog(this, "信号机S1和S2为红色！", "警告", JOptionPane.WARNING_MESSAGE);
//                    return;
//                }
//            }
//
//            if(trackId=="T2"){
//                Signal signal3=signals.get("S3");
//                Signal signalS4=signals.get("S4");
//                if(signal3.getAspect()== Signal.SignalAspect.PROCEED&&signalS4.getAspect()== Signal.SignalAspect.PROCEED){
//                    controller.setTrackCircuitOccupied(trackId, true);
//                }else {
//                    JOptionPane.showMessageDialog(this, "信号机S3和S4为红色！", "警告", JOptionPane.WARNING_MESSAGE);
//                    return;
//                }
//            }
//
//            if(trackId=="T3"){
//                Signal signalS5=signals.get("S5");
//                Signal signalS6=signals.get("S6");
//                if(signalS5.getAspect()== Signal.SignalAspect.PROCEED&&signalS6.getAspect()== Signal.SignalAspect.PROCEED){
//                    controller.setTrackCircuitOccupied(trackId, true);
//                }else {
//                    JOptionPane.showMessageDialog(this, "信号机S5和S6为红色！", "警告", JOptionPane.WARNING_MESSAGE);
//                    return;
//                }
//            }

            controller.setTrackCircuitOccupied(trackId, false);
        });
        add(clearBtn);

        // 进路操作按钮
        add(new JLabel("进路操作:"));
        JButton routeBtn = new JButton("排列进路");
        routeBtn.addActionListener(this::setupRoute);
        add(routeBtn);

        JButton cancelBtn = new JButton("取消进路");
        cancelBtn.addActionListener(e -> {
            String signalId = (String) signalSelector.getSelectedItem();
            controller.cancelRoute("ROUTE_" + signalId);
        });
        add(cancelBtn);
    }

    private void addStatusDisplay() {
        // 状态显示区域
        JTextArea statusArea = new JTextArea(5, 20);
        statusArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(statusArea);



        add(new JLabel("系统状态:"));
        add(scrollPane);

        // 定时刷新状态
        Timer timer = new Timer(1000, e -> {
            StringBuilder sb = new StringBuilder();
            sb.append("道岔状态:\n");
            controller.getSwitches().forEach((id, sw) ->
                    sb.append(String.format("%s: %s %s\n",
                            id,
                            sw.getPosition(),
                            sw.isLocked() ? "(锁定)" : ""))
            );

            sb.append("\n信号机状态:\n");
            controller.getSignals().forEach((id, sig) ->
                    sb.append(String.format("%s: %s\n", id, sig.getAspect()))
            );

            statusArea.setText(sb.toString());
        });
        timer.start();
    }

    private void setupRoute(ActionEvent e) {
        // 创建简单的进路设置对话框
        JDialog dialog = new JDialog();
        dialog.setTitle("排列进路");
        dialog.setLayout(new GridLayout(0, 2, 5, 5));

        // 进路参数设置
        JTextField routeIdField = new JTextField("  ");
        dialog.add(new JLabel("进路ID:"));
        dialog.add(routeIdField);

        JComboBox<String> startSignal = new JComboBox<>(
                controller.getSignals().keySet().toArray(new String[0]));
        dialog.add(new JLabel("起始信号:"));
        dialog.add(startSignal);

        JComboBox<String> endSignal = new JComboBox<>(
                controller.getSignals().keySet().toArray(new String[0]));
        dialog.add(new JLabel("终端信号:"));
        dialog.add(endSignal);

        // 确认按钮
        JButton confirmBtn = new JButton("确认排列");
        confirmBtn.addActionListener(ev -> {
            // 这里应该实现实际的进路排列逻辑
            // 简单示例：只排列起始信号到终端信号的进路
            String routeId = routeIdField.getText();
            String start = (String) startSignal.getSelectedItem();
            Map<String,Train> trainMap=controller.getTrainsController();

            animationTimer=new Timer(50,p ->{      //计时器

                //在这里添加条件判断，如果信号灯P1是绿色的，则可以运行；反正停止
                Map<String,Signal> signalMap=controller.getSignals();
                Signal signalP1=signalMap.get("P1");
                if(signalP1.getAspect()== Signal.SignalAspect.PROCEED){
                    if(signalMap.get("S1").getAspect()== Signal.SignalAspect.PROCEED&&signalMap.get("S2").getAspect()== Signal.SignalAspect.PROCEED){
                        //首先完成了对信号灯的判断，接下来要完成对道岔的判断
                        Route route=controller.getRoutes().get("Route1");
                        if(controller.establishRoute(route)){
                            controller.updateTrains();
                            repaint();
                        }else {
                            repaint();
                        }
//                    controller.updateTrains();
//                    repaint();
                    }

                    if(signalMap.get("S3").getAspect()== Signal.SignalAspect.PROCEED&&signalMap.get("S4").getAspect()== Signal.SignalAspect.PROCEED){
                        Route route=controller.getRoutes().get("Route2");
                        if(controller.establishRoute(route)){
                            controller.updateTrains2();
                            repaint();
                        }else {
                            repaint();
                        }
                        //controller.updateTrains2();

                    }

                    if(signalMap.get("S5").getAspect()== Signal.SignalAspect.PROCEED&&signalMap.get("S6").getAspect()== Signal.SignalAspect.PROCEED){
                        Route route=controller.getRoutes().get("Route3");
                        if(controller.establishRoute(route)){
                            controller.updateTrains3();
                            repaint();
                        }else {
                            repaint();
                        }
                        //controller.updateTrains3();

                    }
                    //controller.updateTrains();
                    repaint();
                }
                repaint();

            });
            animationTimer.start();




            // 实际项目中这里需要计算经过的道岔和轨道区段
            controller.setSignalAspect(start, Signal.SignalAspect.PROCEED);

            JOptionPane.showMessageDialog(dialog, "进路 " + routeId + " 已排列");
            dialog.dispose();
        });
        dialog.add(confirmBtn);

        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }

    public void updateControls() {
        // 更新设备选择器的选项
        switchSelector.setModel(new DefaultComboBoxModel<>(
                controller.getSwitches().keySet().toArray(new String[0])));
        signalSelector.setModel(new DefaultComboBoxModel<>(
                controller.getSignals().keySet().toArray(new String[0])));
        trackSelector.setModel(new DefaultComboBoxModel<>(
                controller.getTrackCircuits().keySet().toArray(new String[0])));
    }
}
